package sysinit

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type DBMessge struct {
	DbType string
	Alias  string
	Name   string
	User   string
	Pwd    string
	Host   string
	Port   string
}

//初始化数据库
func InitDatabase(dbTypes []string) {
	for _, dbType := range dbTypes {
		//读取配置文件
		//数据库类别
		//mysqlInit(getCommonConf("ir_v3"))
		//mysqlInit(getCommonConf("irv3"))
		mysqlInit(getCommonConf(dbType))
	}

}

func getCommonConf(dbType string) DBMessge {
	dbMessge := DBMessge{}
	dbMessge.DbType = dbType
	//连接名称
	dbMessge.Alias = beego.AppConfig.String(dbType + "::db_alias")
	//数据库名称
	dbMessge.Name = beego.AppConfig.String(dbType + "::db_name")
	//数据库连接用户名
	dbMessge.User = beego.AppConfig.String(dbType + "::db_user")
	//数据库连接用户名
	dbMessge.Pwd = beego.AppConfig.String(dbType + "::db_pwd")
	//数据库IP（域名）
	dbMessge.Host = beego.AppConfig.String(dbType + "::db_host")
	//数据库端口
	dbMessge.Port = beego.AppConfig.String(dbType + "::db_port")
	return dbMessge
}

func mysqlInit(messge DBMessge) {
	dbCharset := beego.AppConfig.String(messge.DbType + "::db_charset")
	orm.RegisterDataBase(messge.Alias, "mysql", messge.User+":"+messge.Pwd+"@tcp("+messge.Host+":"+
		messge.Port+")/"+messge.Name+"?charset="+dbCharset, 30)
}
